
//
//  GreenBattlefieldViewController.m
//  LookScore
//
//  Created by wws on 2018/1/18.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//



#import "LSCustomHeaderView.h"
#import "BattlefieldHeaderView.h"
#import "BattlefieldTableViewCell.h"
#import "ConversationDetailController.h"
#import "GreenBattlefieldViewController.h"
#import "PublishIssueTopicViewController.h"
#import "LSTopicCircleModel.h"
#import "LSChatCircleCell.h"
#import "LSChatCircleModel.h"
#import "LSLoginVController.h"
#import "LSTopicCircleDetailModel.h"
#import "LSOtherHomePageViewController.h"
#import "LSPersonalHomePageVController.h"
#import "YBPopupMenu.h"
@interface GreenBattlefieldViewController ()<UITableViewDataSource, UITableViewDelegate,YBPopupMenuDelegate>
@property(strong,nonatomic)NSMutableArray *topicModelArray;//话题模型数组
@property (nonatomic, strong) UITableView * tableView;
@end

@implementation GreenBattlefieldViewController{
    NSInteger          _selectType;//选择类型
    NSInteger          _pageCount;//页数
    NSInteger          _tag;
    BattlefieldHeaderView *_battlefieldView;
    NSIndexPath       *_indexPath;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = LSBackGroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (NSMutableArray *)topicModelArray{
    if (!_topicModelArray) {
        _topicModelArray = @[].mutableCopy;
    }
    
    return _topicModelArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = LSTitleWhiteColor;
    self.title = self.model.Name;
    _selectType = 0;
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .topEqualToView(self.view)
    .bottomEqualToView(self.view);
    //加入子视图
    [self addBattlefieldSubviews];
    [self loadData:YES];
    [self loadTopicCircleDetailData];
    KWeakSelf(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself loadData:YES];
        [weakself loadTopicCircleDetailData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakself loadData:NO];
    }];
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = HOME_INDICATOR_HEIGHT;
    [notifiCenter addObserver:self selector:@selector(updateDate) name:@"LOADCIRCLEDATA" object:nil];
    if (@available(iOS 11.0, *)) {
//        self.tableView.estimatedRowHeight = 0;
//        self.tableView.estimatedSectionHeaderHeight = 0;
//        self.tableView.estimatedSectionFooterHeight = 0;
//        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        self.tableView.contentInset = UIEdgeInsetsMake(0,0,0,0);//64和49自己看效果，是否应该改成0
//        
//        self.tableView.scrollIndicatorInsets = self.tableView.contentInset;

    }
}

/*加入子视图*/
-(void)addBattlefieldSubviews{
    
    
    //绿茵沙场头视图
    _battlefieldView = [[BattlefieldHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 90)];
    _battlefieldView.backgroundColor = LSTitleWhiteColor;
    self.tableView.tableHeaderView = _battlefieldView;
    //发布话题
    NSInteger issueButtonWidth = 70;
    UIImage *issueImageName = [UIImage imageNamed:@"publish_issue_topic"];
    IssueTopicButton *issueTopicButton = [[IssueTopicButton alloc]init];
    [issueTopicButton addTarget:self action:@selector(publishIssueTopicSender:) forControlEvents:UIControlEventTouchUpInside];
    [issueTopicButton setImage:issueImageName forState:UIControlStateNormal];
    issueTopicButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view insertSubview:issueTopicButton aboveSubview:self.tableView];
    
    
    issueTopicButton.sd_layout
    .rightSpaceToView(self.view, 10)
    .bottomSpaceToView(self.view, 30)
    .widthIs(issueButtonWidth)
    .heightIs(issueButtonWidth);
}

#pragma mark -- 加载数据

- (void)loadData:(BOOL)refresh{
    if (refresh) {
        _pageCount = 0;
    }else{
        _pageCount += 1;
    }
    [LSHttpEnclosureTool GET:LSTOPICLIST parameters:@{@"type":@(_selectType),@"pageIndex":@(_pageCount),@"circleId":@(self.model.CircleId),@"cid":self.tokenStr} resBlock:^(id responseObject) {
        if (refresh) {
            [self.topicModelArray removeAllObjects];
        }
        if (responseObject) {
            for (NSDictionary * dict in responseObject[@"TopicList"]) {
                LSChatCircleModel * model = [LSChatCircleModel mj_objectWithKeyValues:dict];
                [self.topicModelArray addObject:model];
            }
            [self.tableView reloadData];
            [CommonClass endRefreshing:self.tableView];
        }else{
            _pageCount -= 1;
            [self.tableView reloadData];
            [CommonClass endRefreshing:self.tableView];
        }
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        
    }];
    
    
    
    
}

- (void)loadTopicCircleDetailData{
    
    [LSHttpEnclosureTool GET:LSTopicCirCleDetail parameters:@{@"id":@(self.model.CircleId)} resBlock:^(id responseObject) {
        if (responseObject) {
            LSTopicCircleDetailModel * model = [LSTopicCircleDetailModel mj_objectWithKeyValues:responseObject];
            _battlefieldView.model = model;
        }
    }];
}

- (void)updateDate{
    [self loadData:YES];
    [self loadTopicCircleDetailData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.topicModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LSChatCircleModel * model = self.topicModelArray[indexPath.row];
    if ([model.ImgUrlStr componentsSeparatedByString:@","].count == 1 && model.ImgUrlStr.length>0) {
        LSChatCircleOneImageViewCell * cell = [LSChatCircleOneImageViewCell ChatCircleOneImageViewCellByTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        KWeakSelf(self);
        cell.block = ^(UIButton *sender) {
//            [weakself attentionAction:indexPath withSender:sender];
            [weakself reportAction:indexPath withSender:sender];
        };
        cell.clickedImageViewBlock = ^{
            if ([LSAccountArchive isLogin]) {
                if ([[LSAccountArchive account].Cid isEqualToString:model.UserCid]) {
                    LSPersonalHomePageVController * personalVc = [[LSPersonalHomePageVController alloc] init];
                    personalVc.userCid = model.UserCid;
                    [weakself.navigationController pushViewController:personalVc animated:YES];
                }else{
                    LSOtherHomePageViewController * otherVC = [[LSOtherHomePageViewController alloc] init];
                    otherVC.userCid = model.UserCid;
                    [weakself.navigationController pushViewController:otherVC animated:YES];
                }
            }else{
                [weakself presentLoginVC];
            }
            
        };
        return cell;
    }else{
        LSChatCircleCell *cell=[LSChatCircleCell ChatCircleTableViewCellByTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        KWeakSelf(self);
        cell.block = ^(UIButton *sender) {
//            [weakself attentionAction:indexPath withSender:sender];
            [weakself reportAction:indexPath withSender:sender];
        };
        cell.clickedImageViewBlock = ^{
            if ([LSAccountArchive isLogin]) {
                LSOtherHomePageViewController * otherVC = [[LSOtherHomePageViewController alloc] init];
                otherVC.userCid = model.UserCid;
                [weakself.navigationController pushViewController:otherVC animated:YES];
            }else{
                [weakself presentLoginVC];
            }
            
        };
        return cell;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    KWeakSelf(self);
    LSCustomHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ChatCircleView"];
    if (!headerView) {
        headerView = [[LSCustomHeaderView alloc] initWithReuseIdentifier:@"ChatCircleView" style:KTableViewHeaderScrollerStyle];
        [headerView  setScrolArray:@[@"全部",@"精选"] spaceWidth:30 titleColor:[CommonClass colorWithHexString:@"#191919"] seletedColor:LSSubColore5735e with:_tag];
        headerView.contentView.backgroundColor = [UIColor whiteColor];
        KWeakSelf(headerView);
        headerView.butonActionBlock = ^(NSInteger tag) {

            if (tag == 0) {
                _selectType = 0;
            }else{
                _selectType = 2;
            }
            [weakself loadData:YES];
            _tag = tag;
        };
        weakheaderView.lineColor=LSNavMainColor;
    }
    //灰色的底线
    UIView  *lineView = [[UIView alloc]init];
    lineView.backgroundColor = LSSubGrayColorf7;
    [headerView addSubview:lineView];
    lineView.sd_layout
    .leftSpaceToView(self, 0)
    .rightEqualToView(headerView)
    .heightIs(1)
    .bottomEqualToView(headerView)
    .rightEqualToView(headerView);

    return headerView;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    LSChatCircleModel * model = self.topicModelArray[indexPath.row];
    if ([model.ImgUrlStr componentsSeparatedByString:@","].count == 1 && model.ImgUrlStr.length>0) {
        return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LSChatCircleOneImageViewCell class] contentViewWidth:[tableView cellContentViewWith]];
    }else{
        return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LSChatCircleCell class] contentViewWidth:[tableView cellContentViewWith]];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LSChatCircleModel * model = self.topicModelArray[indexPath.row];
    ConversationDetailController * conversationVC = [[ConversationDetailController alloc]init];
    conversationVC.TopicId = model.Id;
    conversationVC.cid = self.tokenStr;
    [self.navigationController pushViewController:conversationVC animated:YES];
}

/*前往发布话题*/
- (void)publishIssueTopicSender:(UIButton *)sender{
    if ([LSAccountArchive isLogin]) {
        PublishIssueTopicViewController *publishIssueVC=[[PublishIssueTopicViewController alloc]init];
        publishIssueVC.circleId = self.model.CircleId;
//        KWeakSelf(self);
//        publishIssueVC.block = ^{
//            [weakself loadData:YES];
//            [weakself loadTopicCircleDetailData];
//        };
        [self.navigationController pushViewController:publishIssueVC animated:YES];
    }else{
        
        LSLoginVController *loginVC=[[LSLoginVController alloc]init];
        [self presentRootViewController:loginVC animated:YES completion:nil];
        loginVC.loginSuccessBlock = ^{
            
        };
        
    }
    
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu{
    KWeakSelf(self)
    LSChatCircleModel * model = self.topicModelArray[_indexPath.row];
    if ([LSAccountArchive isLogin]) {
        
        [LSHttpEnclosureTool POST:LSAddUserScreenTopic parameters:@{@"usercid":[LSAccountArchive account].Cid,@"topicId":[NSString stringWithFormat:@"%ld",(long)model.Id]} resBlock:^(id responseObject) {
            if ([responseObject[@"IsSuccess"] integerValue] == 1) {
                [weakself.topicModelArray removeObjectAtIndex:_indexPath.row];
                [weakself.tableView beginUpdates];
                [weakself.tableView deleteRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [weakself.tableView endUpdates];
                [weakself.tableView reloadData];
            }else{
                [MBProgressHUD showOnlyMessage:@"屏蔽失败" afterDelay:1.5f];
            }
            
        }];
    }else{
        [self presentLoginVC];
    }

    
    
}
#pragma mark -- 举报按钮点击事件
- (void)reportAction:(NSIndexPath *)indexPath withSender:(UIButton *)sender{
    
    [YBPopupMenu showRelyOnView:sender titles:@[@"屏蔽"] icons:nil menuWidth:120 delegate:self];
    _indexPath = indexPath;
}

//- (void)attentionAction:(NSIndexPath *)indexPath withSender:(UIButton *)sender{
//
//    LSChatCircleModel * model = self.topicModelArray[indexPath.row];
//    if ([LSAccountArchive isLogin]) {
//        sender.enabled = NO;
//        [LSHttpEnclosureTool POST:LSUserAttention parameters:@{@"cid":model.UserCid,@"fanCid":_tokenStr} resBlock:^(id responseObject) {
//            if ([responseObject integerValue] == 1) {
//
//            }
//            sender.selected = !sender.selected;
//            sender.enabled = YES;
//            [self loadData:YES];
//        }];
//    }else{
//        LSLoginVController *loginVC=[[LSLoginVController alloc]init];
//        [self presentRootViewController:loginVC animated:YES completion:nil];
//        loginVC.loginSuccessBlock = ^{
//            _tokenStr = [LSAccountArchive account].Cid;
//        };
//    }
//}
- (void)presentLoginVC{
    KWeakSelf(self);
    LSLoginVController *loginVC=[[LSLoginVController alloc]init];
    [self presentRootViewController:loginVC animated:YES completion:nil];
    loginVC.loginSuccessBlock = ^{
        [weakself.tableView reloadData];
        _tokenStr = [LSAccountArchive account].Cid;
    };
    
}
- (void)dealloc{
    
    [notifiCenter removeObserver:self];
    MyLog(@"%@ dealloc",NSStringFromClass([self class]));
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
